let App = getApp();
// import html2json from '../../utils/html2json';
// let html2json = require("");
Page({
  data: {
    products: [
    ],
    refresher:false,
    // banner轮播组件属性
    indicatorDots: true, // 是否显示面板指示点	
    autoplay: true, // 是否自动切换
    interval: 3000, // 自动切换时间间隔
    duration: 800, // 滑动动画时长
    imgHeights: {}, // 图片的高度
    imgCurrent: {}, // 当前banne所在滑块指针
    // 页面元素
    ads: {},
    newest: {},
    best: {},
    scrollTop: 0,
    option: {},
    pageNumber: 1,
    scrollHeight: null,
    curNav: 121,
  },

  /**导航菜单的跳转路径**/
  goNav(event) {
    // 跳转商品分类的id
    let id = event.currentTarget.dataset.id;
    let url = '../../pages/product/detail?id=' + id;
    wx.navigateTo({
      url: url,
    })
  },

  onLoad: function (option) {
    wx.showShareMenu({
      withShareTicket:true,
      menus:['shareAppMessage','shareTimeline']
      })
    var that = this;
    // 设置页面标题
    App.setTitle();
    // 设置navbar标题、颜色
    App.setNavigationBar();
    // 获取首页数据
    this.getIndexData();

    // 设置商品列表高度
    that.setListHeight();
    // 记录option
    that.setData({ option }, function () {
      // 获取商品列表
      that.getProductList(true);
    });
    this.setData({'refresher':true})
  },
  onShow(){
    this.getTabBar().setData({
      // 当前页面的 tabBar 索引
      selected: 0
    })
    this.getProductList(true);
  },
  onPullDownRefresh(){
  this.getProductList()
  wx.stopPullDownRefresh();

   
  },
  /**
   * 获取首页数据
   */
  getIndexData: function () {
    let _this = this;
    App._get('/mapi/slide/index', {}, function (result) {
      console.log(result, '轮播图')
      _this.setData({
        "ads": result.data
      });
    });
  },



  /**
   * 获取商品列表
   */
  getProductList: function (is_super, pageNumber) {
    console.log('加载')
    wx.showLoading({
      title: '加载中',
    })
    let _this = this;
    App._get('/mapi/source/index', {
      page: pageNumber || 1,
      orderType: 'PRICE_DESC',
      productCategoryId: 0
    }, function (result) {
      let resultList = result.data
        , dataList = _this.data.products;
      //   console.log(html2json(),'-html2json')
      //  console.log(html2json(resultList[0].title))
    
      _this.setData({ 'products': result.data })

      if (is_super === true || typeof dataList === 'undefined') {
        _this.setData({ list: resultList, noList: false });
      } else {
        _this.setData({ 'products': dataList.concat(resultList) });
      }
      wx.hideLoading()
     
    });
  },

  selectNav: function (t) {
    let curNav = t.target.dataset.id;
    this.setData({
      curNav,
      scrollTop: 0
    });
    console.log(123,'')
    this.getProductList(true);
  },

  /**
 * 下拉到底加载数据
 */
  bindDownLoad: function () {
    if (this.data.pageNumber >= this.data.lastPage) {
      this.setData({ no_more: true });
      return false;
    }
    this.getProductList(false, ++this.data.pageNumber);
  },

  /**
   * 设置商品列表高度
   */
  setListHeight: function () {
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          scrollHeight: res.windowHeight - 90,
        });
      }
    });
  },


  /**
   * 计算图片高度
   */
  imagesHeight: function (e) {
    let imgId = e.target.dataset.id,
      itemKey = e.target.dataset.itemKey,
      ratio = e.detail.width / e.detail.height, // 宽高比
      viewHeight = 750 / ratio, // 计算的高度值
      imgHeights = this.data.imgHeights;

    // 把每一张图片的对应的高度记录到数组里
    if (typeof imgHeights[itemKey] === 'undefined') {
      imgHeights[itemKey] = {};
    }
    imgHeights[itemKey][imgId] = viewHeight;
    // 第一种方式
    let imgCurrent = this.data.imgCurrent;
    if (typeof imgCurrent[itemKey] === 'undefined') {
      imgCurrent[itemKey] = Object.keys(this.data.ads[0]);
    }
    this.setData({
      imgHeights,
      imgCurrent
    });
  },

  bindChange: function (e) {
    let itemKey = e.target.dataset.itemKey,
      imgCurrent = this.data.imgCurrent;
    // imgCurrent[itemKey] = e.detail.current;
    imgCurrent[itemKey] = e.detail.currentItemId;
    this.setData({
      imgCurrent
    });
  },

  goTop: function (t) {
    this.setData({
      scrollTop: 0
    });
  },

  scroll: function (t) {
    // this.setData({
    //   indexSearch: t.detail.scrollTop
    // }), t.detail.scrollTop > 300 ? this.setData({
    //   floorstatus: !0
    // }) : this.setData({
    //   floorstatus: !1
    // });
  },

  like: function (id) {

  },

  //分享到朋友圈
  onShareAppMessage: function (res) {
    let _this = this;
    const id = res.target.dataset.id
    if (res.from === 'button') {
      console.log(res.target)
    }
    return {
      title: '半亩花田',
      path: "/pages/product/detail?id=" + id
    }
  },

  
  /**
   * setlike
   */

  setlike: function (event) {
    console.log(event, '--event')
    const _this = this
    const source_id = event.currentTarget.dataset.source_id
    const index = event.currentTarget.dataset.index
    console.log(source_id, '--source_id')
    App._get('/mapi/user_operate/dolike', { source_id: source_id }, function (result) {
      if (result.code == 200) {
        const products = _this.data.products;
        if (products[index].user_like_state==0) {
          products[index].like_num += 1;
          products[index].user_like_state = 1
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '点赞成功',
          })
        }else{
          products[index].like_num -= 1;
          products[index].user_like_state = 0;
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '取消点赞',
          })
        }
      }else{
        // 请登录
       App.doLogin()

      }
    })
  },
  setcollect: function (event) {
    const _this = this
    const source_id = event.currentTarget.dataset.source_id
    const index = event.currentTarget.dataset.index
    App._get('/mapi/user_operate/docollect', { source_id: source_id }, function (result) {
      if (result.code == 200) {
        const products = _this.data.products;
        if (products[index].user_collect_state==0) {
          products[index].collect_num += 1;
          products[index].user_collect_state = 1
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '收藏成功',
          })
        }else{
          products[index].collect_num -= 1;
          products[index].user_collect_state = 0;
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '取消收藏',
          })
        }
      }else{
        App.doLogin()
      }
    })
  },
   async download  (event) {
    const index = event.currentTarget.dataset.index
    const type =  this.data.products[index].type
    const text = this.data.products[index].title
    App.copyText(text)
    const file = this.data.products[index].content
    for (let index = 0; index < file.length; index++) {
      const element = file[index];
       await App.download(element,type)
    }
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });
      
  },
  /**
   * 图片预览
   */
  preview: function(event){
    const src = event.currentTarget.dataset.src
    const url = event.currentTarget.dataset.url
    wx.previewImage({
      current: this.data.products[src].content[url],
      urls: this.data.products[src].content,
    })
  }
});